package com.chuantou.yuba.ui;

import java.io.File;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request.Method;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.baidu.location.BDLocation;
import com.chuantou.yuba.R;
import com.chuantou.yuba.YBApp;
import com.chuantou.yuba.adapter.ExpressionAdapter;
import com.chuantou.yuba.adapter.ExpressionPagerAdapter;
import com.chuantou.yuba.api.RequestManager;
import com.chuantou.yuba.api.UriHelper;
import com.chuantou.yuba.api.request.MultiPartRequest;
import com.chuantou.yuba.api.to.BDPoiTO;
import com.chuantou.yuba.api.to.BaseTO;
import com.chuantou.yuba.api.to.UserTO;
import com.chuantou.yuba.ui.widget.ExpandGridView;
import com.chuantou.yuba.ui.widget.KeyboardLayout;
import com.chuantou.yuba.util.AccountManager;
import com.chuantou.yuba.util.Constants;
import com.chuantou.yuba.util.FileUtil;
import com.chuantou.yuba.util.ImageUtil;
import com.chuantou.yuba.util.MediaUtil;
import com.chuantou.yuba.util.UiUtil;
import com.easemob.applib.utils.SmileUtils;

public class PublishTrendsActivity extends BaseActionBarActivity implements OnClickListener {
	private static final int MAX_PIC_NUMBER = 9;
	public static final File CACHE_DIR = FileUtil.getImageCacheDir();
	public static final int REQUEST_CODE_CAPTURE = 20000;
	public static final int REQUEST_CODE_GALLERY = 20001;
	public static final int REQUEST_CODE_LOCATION = 20002;
	public static final int REQUEST_CODE_ALBUM = 20003;
	private RecyclerView mRecyclerView;
	private ImageAdapter mAdapter;
	private String mCapturePath = null;
	private int mScreenWidth;
	private int mScreenHeight;
	private ImageView mCaptureMenu;
	private ImageView mGalleryMenu;
	private BDPoiTO mPoi;
	private View mLocationLayout;
	private TextView mLocationNameView;
	private EditText mContentView;
	private KeyboardLayout mKeyboardLayout;
	private ProgressDialog mDialog;
	private ViewPager mExpressionViewpager;
	private LinearLayout mEmojiContainer;
	private List<String> reslist;
	private Map<String, Bitmap> mBitmapCache = new HashMap<String, Bitmap>();
	private ImageView mAddEmojiView;
	private ImageView mShowKeyboardView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.publish_trends);
		DisplayMetrics dm = new DisplayMetrics();
		YBApp.get().startLocate(null);
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		mScreenWidth = dm.widthPixels;
		mScreenHeight = dm.heightPixels;
		setupViews();
		// 删除过期图片
		setTitle(R.string.publish_trends);
		deleteUnUseImage();
	}

	private void setupViews() {
		mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
		LinearLayoutManager layoutManager = new LinearLayoutManager(this);
		layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
		mRecyclerView.setLayoutManager(layoutManager);
		mAdapter = new ImageAdapter();
		mRecyclerView.setAdapter(mAdapter);
		mCaptureMenu = (ImageView) findViewById(R.id.menu_capture);
		mCaptureMenu.setOnClickListener(this);
		mGalleryMenu = (ImageView) findViewById(R.id.menu_gallery);
		mGalleryMenu.setOnClickListener(this);
		findViewById(R.id.menu_location).setOnClickListener(this);
		mLocationLayout = findViewById(R.id.location_layout);
		mLocationNameView = (TextView) findViewById(R.id.location);
		findViewById(R.id.delete_location).setOnClickListener(this);
		mContentView = (EditText) findViewById(R.id.content);
		mEmojiContainer = (LinearLayout) findViewById(R.id.ll_face_container);
		mAddEmojiView = (ImageView) findViewById(R.id.add_emoji);
		mAddEmojiView.setOnClickListener(this);
		mShowKeyboardView = (ImageView) findViewById(R.id.show_keyboard);
		mShowKeyboardView.setOnClickListener(this);
		mKeyboardLayout = (KeyboardLayout) findViewById(R.id.root);
		mKeyboardLayout.setOnkbdStateListener(new KeyboardLayout.onKybdsChangeListener() {

			@Override
			public void onKeyBoardStateChange(int state) {
				switch (state) {
				case KeyboardLayout.KEYBOARD_STATE_HIDE:
					if (mEmojiContainer.getVisibility() != View.VISIBLE) {
						mEmojiContainer.setVisibility(View.GONE);
						mAddEmojiView.setSelected(false);
					}
					break;
				case KeyboardLayout.KEYBOARD_STATE_SHOW:
					break;
				default:
					break;
				}
			}
		});
		// 表情list
		reslist = getExpressionRes(35);
		// 初始化表情viewpager
		List<View> views = new ArrayList<View>();
		View gv1 = getGridChildView(1);
		View gv2 = getGridChildView(2);
		views.add(gv1);
		views.add(gv2);
		mExpressionViewpager = (ViewPager) findViewById(R.id.vPager);
		mExpressionViewpager.setAdapter(new ExpressionPagerAdapter(views));
	}

	public List<String> getExpressionRes(int getSum) {
		List<String> reslist = new ArrayList<String>();
		for (int x = 1; x <= getSum; x++) {
			String filename = "ee_" + x;
			reslist.add(filename);
		}
		return reslist;

	}

	/**
	 * 获取表情的gridview的子view
	 * 
	 * @param i
	 * @return
	 */
	private View getGridChildView(int i) {
		View view = View.inflate(this, R.layout.expression_gridview, null);
		ExpandGridView gv = (ExpandGridView) view.findViewById(R.id.gridview);
		List<String> list = new ArrayList<String>();
		if (i == 1) {
			List<String> list1 = reslist.subList(0, 20);
			list.addAll(list1);
		} else if (i == 2) {
			list.addAll(reslist.subList(20, reslist.size()));
		}
		list.add("delete_expression");
		final ExpressionAdapter expressionAdapter = new ExpressionAdapter(this, 1, list);
		gv.setAdapter(expressionAdapter);
		gv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				String filename = expressionAdapter.getItem(position);
				try {
					// 文字输入框可见时，才可输入表情
					// 按住说话可见，不让输入表情
					if (filename != "delete_expression") { // 不是删除键，显示表情
						// 这里用的反射，所以混淆的时候不要混淆SmileUtils这个类
						Class clz = Class.forName(SmileUtils.class.getName());
						Field field = clz.getField(filename);
						mContentView.append(SmileUtils.getSmiledText(getApplicationContext(), (String) field.get(null)));
					} else { // 删除文字或者表情
						mContentView.onKeyDown(KeyEvent.KEYCODE_DEL, new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL));
					}
				} catch (Exception e) {
				}

			}
		});
		return view;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.menu_publish, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_publish:
			preparePublish();
			return true;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	private void deleteUnUseImage() {
		File[] files = CACHE_DIR.listFiles();
		if (files != null && files.length > 0) {
			for (File file : files) {
				if ((System.currentTimeMillis() - file.lastModified()) > 24 * 60 * 60 * 1000) {
					file.delete();
				}
			}
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.menu_capture:
			startImageCaptureActivity();
			break;
		case R.id.menu_gallery:
		// startImageLocalPickActivity();
		{
			Intent intent = new Intent(this, AlbumActivity.class);
			intent.putExtra(Constants.EXTRA_SIZE, MAX_PIC_NUMBER - mAdapter.getItemCount());
			startActivityForResult(intent, REQUEST_CODE_ALBUM);
		}
			break;
		case R.id.menu_location:
			Intent intent = new Intent(this, PickLocationActivity.class);
			startActivityForResult(intent, REQUEST_CODE_LOCATION);
			break;
		case R.id.delete: {
			Object obj = v.getTag();
			String tag = obj == null ? null : String.valueOf(obj);
			if (!TextUtils.isEmpty(tag) && TextUtils.isDigitsOnly(tag)) {
				int position = Integer.parseInt(tag);
				mAdapter.remove(position);
				mAdapter.notifyDataSetChanged();
				checkCanAddImage();
			}
		}
			break;
		case R.id.delete_location:
			mPoi = null;
			mLocationLayout.setVisibility(View.GONE);
			break;
		case R.id.add_emoji:
			if (UiUtil.isFastDoubleClick())
				return;
			mShowKeyboardView.setVisibility(View.VISIBLE);
			mAddEmojiView.setVisibility(View.GONE);
			mEmojiContainer.setVisibility(View.VISIBLE);
			UiUtil.hideInputKeyboard(this, mContentView);
			break;
		case R.id.show_keyboard:
			if (UiUtil.isFastDoubleClick())
				return;
			mShowKeyboardView.setVisibility(View.GONE);
			mAddEmojiView.setVisibility(View.VISIBLE);
			mEmojiContainer.setVisibility(View.GONE);
			UiUtil.showInputKeyboard(this, mContentView);
			break;
		default:
			break;
		}
	}

	private void preparePublish() {
		if (UiUtil.isFastDoubleClick())
			return;
		final String content = mContentView.getText().toString().trim();
		List<String> images = mAdapter.getPaths();
		if (TextUtils.isEmpty(content) && images.isEmpty()) {
			Toast.makeText(this, R.string.trends_input_error, Toast.LENGTH_SHORT).show();
			return;
		}
		AccountManager accountManager = AccountManager.getInstance(getApplicationContext());
		if (!accountManager.isLogined()) {
			UiUtil.showNoLoginDialog(this, -1, LoginActivity.ACTION_RETURN);
			return;
		}
		final UserTO user = accountManager.getUserTO();
		if (user.isExpired()) {
			Toast.makeText(this, R.string.message_token_expired, Toast.LENGTH_SHORT).show();
			LoginActivity.start(this, -1, LoginActivity.ACTION_RETURN);
			return;
		}
		new AsyncTask<Void, Void, List<String>>() {
			protected void onPreExecute() {
				mDialog = new ProgressDialog(PublishTrendsActivity.this);
				mDialog.setMessage(getString(R.string.trends_sending));
				mDialog.setCancelable(false);
				mDialog.show();
			};

			@Override
			protected List<String> doInBackground(Void... params) {
				// 把图片转成jpg并压缩到指定大小
				File cacheDir = FileUtil.getImageCacheDir();
				Random random = new Random(1000);
				List<String> paths = mAdapter.getPaths();
				List<String> newPaths = new ArrayList<String>();
				if (paths != null && !paths.isEmpty()) {
					for (String path : paths) {
						String name = String.format("%d_%d.jpg", System.currentTimeMillis(), random.nextInt());
						String newPath = new File(cacheDir, name).getAbsolutePath();
						ImageUtil.generateThumb(path, newPath, mScreenWidth, mScreenHeight);
						newPaths.add(newPath);
					}
				}
				return newPaths;
			}

			protected void onPostExecute(List<String> paths) {
				sendTrends(user, paths, content);
			};

		}.execute();
	}

	private void sendTrends(UserTO user, final List<String> paths, String content) {
		String url = UriHelper.getAddTrendsUrl();
		MultiPartRequest<BaseTO> request = new MultiPartRequest<BaseTO>(Method.POST, url, new Listener<BaseTO>() {

			@Override
			public void onResponse(BaseTO response) {
				// 删除压缩的图片
				FileUtil.deleteFiles(paths);
				if (!hasDestroyed()) {
					if (mDialog != null && mDialog.isShowing()) {
						mDialog.dismiss();
					}
					if (response != null) {
						if (response.isSuccess()) {
							Toast.makeText(getApplicationContext(), R.string.send_success, Toast.LENGTH_SHORT).show();
							sendBroadcast(new Intent(Constants.INTENT_ACTION_SEND_TRENDS));
							finish();
						} else {
							if (response.getStatus() == BaseTO.STATUS_TOKEN_ERROR || response.getStatus() == BaseTO.STATUS_TOKEN_EXPIRED) {
								Toast.makeText(getApplicationContext(), R.string.message_token_expired, Toast.LENGTH_SHORT).show();
								LoginActivity.start(PublishTrendsActivity.this, -1, LoginActivity.ACTION_RETURN);
							} else {
								String msg = response.getMsg();
								msg = TextUtils.isEmpty(msg) ? getString(R.string.send_failed) : msg;
								Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
							}
						}
					} else {
						Toast.makeText(getApplicationContext(), R.string.send_failed, Toast.LENGTH_SHORT).show();
					}
				}
			}
		}, new ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError error) {
				// 删除压缩的图片
				FileUtil.deleteFiles(paths);
				if (!hasDestroyed()) {
					if (mDialog != null && mDialog.isShowing()) {
						mDialog.dismiss();
					}
					Toast.makeText(getApplicationContext(), R.string.request_error, Toast.LENGTH_SHORT).show();
				}
			}
		}, BaseTO.class);
		request.addStringUpload(UriHelper.PARAMS_UID, String.valueOf(user.getUid()));
		request.addStringUpload(UriHelper.PARAMS_TOKEN, user.getToken());
		request.addStringUpload(UriHelper.PARAMS_CONTENT, content);
		int counter = 1;
		for (String path : paths) {
			File file = new File(path);
			if (file.exists()) {
				request.addFileUpload("picture" + counter, file);
				counter++;
			}
		}
		String address = mPoi == null ? "" : mPoi.getName();
		String point = mPoi == null ? "" : mPoi.getLocation().getLongitude() + "," + mPoi.getLocation().getLatitude();
		if (TextUtils.isEmpty(point)) {
			BDLocation location = YBApp.get().getLocation();
			if (location != null) {
				point = location.getLongitude() + "," + location.getLatitude();
			}
		}
		request.addStringUpload(UriHelper.PARAMS_ADDRESS, address);
		request.addStringUpload(UriHelper.PARAMS_POINT, point);
		RequestManager.startUpload(getApplicationContext(), request);
	}

	private void startImageCaptureActivity() {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		String fileName = String.format("%d.jpg", System.currentTimeMillis());
		File file = new File(CACHE_DIR, fileName);
		mCapturePath = file.getAbsolutePath();
		intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
		startActivityForResult(intent, REQUEST_CODE_CAPTURE);
	}

	private void startImageLocalPickActivity() {
		Intent i = new Intent(Intent.ACTION_GET_CONTENT).setType("image/*");
		startActivityForResult(i, REQUEST_CODE_GALLERY);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_CANCELED) {
			// 删除拍照的原图;
			if (mCapturePath != null) {
				new File(mCapturePath).delete();
				mCapturePath = null;
			}
			return;
		}
		// 根据上面发送过去的请求码来区别
		switch (requestCode) {
		case REQUEST_CODE_CAPTURE: // take photo;
		{
			String path = mCapturePath;
			mCapturePath = null;
			mAdapter.add(path);
			mAdapter.notifyDataSetChanged();
			mRecyclerView.getLayoutManager().scrollToPosition(mAdapter.getItemCount() - 1);
			checkCanAddImage();
		}
			break;
		case REQUEST_CODE_GALLERY: // local photo;
		{
			Uri selectedImage = data.getData();
			String path = MediaUtil.getPath(this, selectedImage);
			mAdapter.add(path);
			mAdapter.notifyDataSetChanged();
			mRecyclerView.getLayoutManager().scrollToPosition(mAdapter.getItemCount() - 1);
			checkCanAddImage();
		}
			break;
		case REQUEST_CODE_LOCATION: {
			if (data != null) {
				mPoi = data.getParcelableExtra(Constants.EXTRA_DATA);
				if (mPoi != null) {
					mLocationLayout.setVisibility(View.VISIBLE);
					mLocationNameView.setText(mPoi.getName());
				}
			}
		}
			break;
		case REQUEST_CODE_ALBUM:
			if (data != null) {
				ArrayList<String> paths = data.getStringArrayListExtra(Constants.EXTRA_DATA);
				if (paths != null && !paths.isEmpty()) {
					for (String path : paths) {
						mAdapter.add(path);
					}
					mAdapter.notifyDataSetChanged();
					checkCanAddImage();
					mRecyclerView.getLayoutManager().scrollToPosition(mAdapter.getItemCount() - 1);
				}
			}
			break;
		default:
			break;
		}

	}

	private void checkCanAddImage() {
		if (mAdapter.getItemCount() >= MAX_PIC_NUMBER) {
			mGalleryMenu.setEnabled(false);
			mCaptureMenu.setEnabled(false);
		} else {
			mGalleryMenu.setEnabled(true);
			mCaptureMenu.setEnabled(true);
		}
	}

	@Override
	public void finish() {
		FileUtil.deleteFile(CACHE_DIR);
		super.finish();
	}

	@Override
	protected void onDestroy() {
		for (String key : mBitmapCache.keySet()) {
			mBitmapCache.get(key).recycle();
		}
		mBitmapCache.clear();
		YBApp.get().stopLocate(false);
		super.onDestroy();
	}

	private class ImageAdapter extends RecyclerView.Adapter<ImageHolder> {
		private List<String> mPaths = new ArrayList<String>();
		int mMaxWidth = getResources().getDimensionPixelSize(R.dimen.send_trend_thumnail_width);

		public List<String> getPaths() {
			return mPaths;
		}

		@Override
		public int getItemCount() {
			return mPaths.size();
		}

		public void add(String path) {
			mPaths.add(path);
		}

		public void clear() {
			mPaths.clear();
			notifyDataSetChanged();
		}

		public void remove(int position) {
			mPaths.remove(position);
			mAdapter.notifyDataSetChanged();
		}

		@Override
		public void onBindViewHolder(ImageHolder holder, int position) {
			String path = mPaths.get(position);
			Bitmap bitmap = mBitmapCache.get(path);
			if (bitmap == null) {
				bitmap = ImageUtil.decodeSampledBitmapFromFile(path, mMaxWidth, mMaxWidth);
				if (bitmap != null) {
					mBitmapCache.put(path, bitmap);
				}
			}
			holder.getImageView().setImageBitmap(bitmap);
			holder.getDeleteImageView().setTag(position);
		}

		@Override
		public ImageHolder onCreateViewHolder(ViewGroup parent, int position) {
			View view = View.inflate(parent.getContext(), R.layout.image_item, null);
			return new ImageHolder(view);
		}

	}

	class ImageHolder extends RecyclerView.ViewHolder {
		private ImageView mImageView;
		private ImageView mDeleteView;

		public ImageHolder(View itemView) {
			super(itemView);
			mImageView = (ImageView) itemView.findViewById(R.id.image);
			mDeleteView = (ImageView) itemView.findViewById(R.id.delete);
			mDeleteView.setOnClickListener(PublishTrendsActivity.this);
		}

		public ImageView getImageView() {
			return mImageView;
		}

		public ImageView getDeleteImageView() {
			return mDeleteView;
		}
	}

}
